import { Form, Input, Button } from 'antd';
import { useNavigate } from 'react-router-dom';
import { useLayoutEffect, useRef } from 'react';
import { setUserInfo, post } from '@/store/counterSlice';
import { logining } from '@/apis/user';
import { useDispatch, useSelector } from 'react-redux';

const index = () => {
  const router = useNavigate();
  const { token } = useSelector((state) => state.counter.userInfo);
  const isLoginRedirect = useRef(false);
  const dispatch = useDispatch();
  useLayoutEffect(() => {
    if (token) {
      isLoginRedirect.current ? router('/') : router(-1); //如果是表单登录成功设置的 token → 跳首页
    }
  }, [token]);

  // 验证通过登陆
  const onFinish = async (values) => {
    const { payload } = await dispatch(post(logining(values)));
    if (payload.code === 200) {
      isLoginRedirect.current = true;
      dispatch(
        setUserInfo({
          token: payload.token,
          user_name: payload.user_name,
          permissionCode: [...payload.permissionCode],
        })
      );
    }
  };

  const mapFormElemment = [
    {
      name: 'user_name',
      element: <Input placeholder="账号" />,
      rules: [{ required: true, message: '请输入账号' }],
    },
    {
      name: 'password',
      element: <Input placeholder="密码" />,
      rules: [{ required: true, message: '请输入密码' }],
    },
  ];

  return (
    <>
      <div
        className="h-full flex"
        style={{
          background: 'linear-gradient(135deg,#52E5E7 15%,#130CB7 100%)',
        }}
      >
        <div className="m-auto w-[300px] p-[10px]">
          <Form labelCol={{ span: 5 }} onFinish={onFinish}>
            {mapFormElemment.map((item) => (
              <Form.Item name={item.name} rules={item.rules} key={item.name}>
                {item.element}
              </Form.Item>
            ))}
            <Form.Item>
              <Button htmlType="submit" block color="primary">
                登录
              </Button>
            </Form.Item>
          </Form>
        </div>
      </div>
    </>
  );
};
export default index;
